<template>
  <ex-dialog @close="closePosition" v-model="visible" draggable :title="form.positionName ? form.positionName : (form.id ? form.positionName : '新增')"
  width="700" :contentHeight="450">
  <template #default>
      <el-tabs v-model="activeName"  style="height: 100%;">
        <el-tab-pane label="基本信息" name="base" style="height: 100%;">
          <el-row :gutter="80">
            <el-col :lg="24">
              <el-form :model="form" :rules="button_rules" ref="dialogForm" label-width="100px" label-position="left">
<!--                <el-form-item label="位置编码" prop="positionCode">-->
<!--                  <el-input v-model="form.positionCode" clearable placeholder="位置编码"></el-input>-->
<!--                </el-form-item>-->
				  <el-form-item label="上级位置" prop="parentLevelCode">
					  <ex-cascader @change="changeParentLevel" :disabled="form.id ? false : true" v-model="form.parentLevelCode" dict-code="FamsPosition" key-prop="levelCode" :clearable="false" placeholder="默认所有"></ex-cascader>
				  </el-form-item>
				  <el-form-item label="位置类型" v-if="parentPositionType == 1" prop="positionType">
					  <el-select v-model="form.other.positionType" clearable placeholder="请选择位置类型">
						  <el-option label="楼宇" value="2"></el-option>
						  <el-option label="详细地址" value="4"></el-option>
					  </el-select>
				  </el-form-item>
				  <el-form-item label="位置类型" v-if="parentPositionType == 2" prop="positionType">
					  <el-select v-model="form.other.positionType" clearable placeholder="请选择位置类型">
						  <el-option label="楼层房间" value="3"></el-option>
						  <el-option label="详细地址" value="4"></el-option>
					  </el-select>
				  </el-form-item>
				  <el-form-item label="位置名称" v-if="!form.other.positionType" prop="positionName">
					  <el-input v-model="form.positionName" clearable placeholder="位置名称"></el-input>
				  </el-form-item>
				  <template v-if="form.other.positionType == 2">
					  <el-form-item label="楼宇/门牌号" prop="houseNumber">
						  <el-input v-model="form.other.houseNumber" clearable placeholder="楼宇/门牌号"></el-input>
					  </el-form-item>
				  </template>
				  <template v-if="form.other.positionType == 3">
					  <el-form-item label="楼层" prop="floorNumber">
						  <el-input type="number" v-model="form.other.floorNumber" clearable placeholder="楼层"></el-input>
					  </el-form-item>
					  <el-form-item label="房间" prop="roomNumber">
						  <el-input v-model="form.other.roomNumber" clearable placeholder="房间"></el-input>
					  </el-form-item>
				  </template>
				  <template v-if="form.other.positionType == 4">
					  <el-form-item label="详细地址" prop="address">
						  <el-input v-model="form.other.address" clearable placeholder="详细地址"></el-input>
					  </el-form-item>
				  </template>
                <el-form-item label="排序" prop="orderWeight">
                <el-input v-model="form.orderWeight" clearable placeholder="排序"></el-input>
                </el-form-item>
              </el-form>

            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="关联部门" name="SysRole" style="height: 100%">
          <ex-rel-table ref="deptRelTable" size="small" :rel-entity="form" :treeApi="this.$API.system.dept.treeData" default-expand-all>
            提示: 默认所有部门不可用，若勾选之后，则只有勾选部门可用
          </ex-rel-table>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <div style="flex: auto;text-align: center">
        <el-button plain type="primary" @click="save" :loading="loading">保 存</el-button>
        <el-button plain type="warning" @click="reset" :loading="loading">重 置</el-button>
        <el-button plain type="info" @click="closePosition" :loading="loading">关 闭</el-button>
      </div>
    </template>

  </ex-dialog>
</template>

<script>
import scIconSelect from '@/components/scIconSelect'
import ExRelTable from "@/components/exRelTable/index.vue";
import ExCascader from "@/components/exCascader/index.vue";
import exDialog from '@/components/exDialog';

export default {
  computed: {
  },
  emits: ['success'],
  components: {
    ExCascader,
    ExRelTable,
    scIconSelect,
    exDialog
  },
  props: {
    menu: {
      type: Object, default: () => {
      }
    },
  },
  data() {
    return {
      activeName: 'base',
      visible: false,
      form: {
        id: "",
        positionCode: "",
        positionName: "",
        positionAddress: "",
		  other:{
			  houseNumber:"",
			  roomNumber:"",
			  address:""
		  },
        parentLevelCode:""
      },
		parentPositionType: '',
      positionOptions: [],
      positionProps: {
        value: 'levelCode',
        label: 'label',
        checkStrictly: true,
        emitPath:false,
      },
		lastLevelAddress: "",
      button_rules: {
      },
      loading: false,
      oldForm: null,
    }
  },
  watch: {},
  mounted() {
  },
  onLoad() {
  },
  methods: {
    //显示
    open(entity) {
		this.form = {};
		if(!entity.other){
			entity.other = {}
		}
		if(entity.other.positionType){
			this.parentPositionType = parseInt(entity.other.positionType) - 1;
		}
		this.lastLevelAddress = {};
		this.form = this.$TOOL.objCopy(entity);
		this.oldForm = this.$TOOL.objCopy(this.form);
		this.visible = true;
		this.activeName = "base";
      // this.loadtree();
    },
	  closePosition() {
		  this.reset();
		  this.visible = false;
	  },
    reset() {
		this.form = this.$TOOL.objCopy(this.oldForm);
		this.parentPositionType = '';
		this.form.other = {};
		for(let ref in this.$refs){
			try {
				this.$refs[ref].refresh();
			}catch (e){
			}
		}
    },
    async loadtree() {
		this.positionOptions = await this.$cache.tree.reload(this.$API.system.position.treeData.storeName, {});
		this.addDisabled(this.positionOptions);
    },
	  async changeParentLevel(){
		  this.loading = true;
		  let queryParams = {};
		  queryParams.levelCode = this.form.parentLevelCode;
		  let pathCode = this.form.pathCode.split(",");
		  try {
			  let res = await this.$API.system.position.findOne.post(queryParams);
			  if (res.code === 2000) {
				  this.loading = false;
				  if (res.data && res.data.other && !res.data.other.positionType) {
					  this.$message.warning("选中的上级位置不能挂载当前位置，请选择其他上级位置");
					  this.form.parentLevelCode = pathCode[pathCode.length - 1];
					  return;
				  }
				  let parentPositionType = res.data.other.positionType;
				  if (parentPositionType == '4') {
					  this.$message.warning("该上级菜单不能挂载位置，请选择其他上级位置");
					  this.form.parentLevelCode = pathCode[pathCode.length - 1];
					  return;
				  }
				  if (parentPositionType == '3' && this.form.other.positionType == '2') {
					  this.$message.warning("楼层房间菜单不能挂载楼宇位置，请选择其他上级位置");
					  this.form.parentLevelCode = pathCode[pathCode.length - 1];
					  return;
				  }
				  if (parentPositionType == this.form.other.positionType) {
					  this.$message.warning("该位置和上级位置相同，请选择其他上级菜单");
					  this.form.parentLevelCode = pathCode[pathCode.length - 1];
					  return;
				  }
				  if (parentPositionType == '1' && this.form.other.positionType == '3') {
					  this.$message.warning("区级菜单不能挂载楼层房间位置，请选择其他上级位置");
					  this.form.parentLevelCode = pathCode[pathCode.length - 1];
					  return;
				  }
				  this.parentPositionType = res.data.other.positionType;
				  this.lastLevelAddress = res.data.positionAddress;
				  this.form.parentLevelCode = res.data.levelCode;
			  } else {
				  this.$message.warning("数据加载失败，请稍后重新");
				  this.loading = false;
			  }
		  } catch (e){
			  this.$message.warning("数据加载失败，请稍后重新");
		  }finally {
			  this.loading = false;
		  }
	  },
    addDisabled(datas){
      datas.forEach(item=>{
        item.disabled = item.isEnabled !== '1';
        if(item.children){
          this.addDisabled(item.children);
        }
      })
    },
    //保存
    async save() {
		try {
			if(this.form.other.positionType == 2){
				//楼宇
				if(!this.form.other.houseNumber){
					this.$message.warning("请输入楼宇/门牌号");
					return;
				}
				this.form.other.isCanCreate = '1';
				this.form.positionName = this.form.other.houseNumber;
			}else if(this.form.other.positionType == 3){
				if(!this.form.other.floorNumber){
					this.$message.warning("请输入楼层");
					return;
				}
				if(this.form.other.roomNumber){
					this.form.positionName = this.form.other.floorNumber + "楼" + this.form.other.roomNumber;
				}else {
					this.form.positionName = this.form.other.floorNumber + "楼";
				}
				this.form.other.isCanCreate = '1';
			}else if(this.form.other.positionType == 4){
				if(!this.form.other.address){
					this.$message.warning("请输入详细地址");
					return;
				}
				this.form.positionName = this.form.other.address;

				this.form.other.isCanCreate = '0';
				this.form.isEnabled = '1';
			}else{
				this.form.other.positionType = null;
			}
			//验证名称是否重复(9.6号更新)
			// let queryParams = {};
			// queryParams.positionName = this.form.positionName;
			// queryParams.parentLevelCode = this.form.parentLevelCode;
			// let checkRes = await this.$API.system.position.listData.post(queryParams);
			// if (checkRes.code === 2000) {
			// 	if(checkRes.data.length > 0){
			// 		if (!this.form.id) {
			// 			this.$message.warning("该位置名称已存在,请输入其他名称");
			// 			return;
			// 		}else{
			// 			if(this.oldForm.parentLevelCode !== this.form.parentLevelCode){
			// 				this.$message.warning("您选择的父节点下有相同名称位置，请修改位置名称");
			// 				return;
			// 			}else {
			// 				this.$message.warning("该位置名称已存在,请输入其他名称");
			// 				return;
			// 			}
			// 		}
			//
			// 	}
			// }else {
			// 	this.$message.warning("请重新尝试");
			// 	return;
			// }
			if (!this.form.id) {
				this.form.positionAddress = this.form.positionAddress + "/"+ this.form.positionName;
			}else{
				if(this.oldForm.parentLevelCode !== this.form.parentLevelCode){
					this.form.positionAddress = this.lastLevelAddress + "/"+ this.form.positionName;
				}else{
					let oldPositionAddress = this.$TOOL.objCopy(this.oldForm).positionAddress;
					let parentAddress = oldPositionAddress.substring(0,oldPositionAddress.lastIndexOf("/"))
					this.form.positionAddress = parentAddress + "/"+ this.form.positionName;
				}
			}

			this.loading = true
			let res;
			if (this.form.id) {
			  res = await this.$API.system.position.updatePosition.post(this.form)
			} else {
			  res = await this.$API.system.position.add.post(this.form)
			}
			if (res.code === 2000) {
			  this.$message.success(this.$t("code."+res.code));
			this.$emit('success');
			  this.visible = false;
			this.$store.dispatch("commit",this.form.entityName);
			} else {
			  this.$message.warning(res.message)
			}
		} finally {
			this.loading = false
		}
    },
  }
}
</script>

<style scoped>
h2 {
  font-size: 17px;
  color: #3c4a54;
  padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
  color: #fff;
}

</style>
